package cn.yan.luowowo.service.impl;

import cn.yan.luowowo.cache.service.UserInfoRedisService;
import cn.yan.luowowo.domain.UserInfo;
import cn.yan.luowowo.exception.LogicException;
import cn.yan.luowowo.repository.UserInfoRepository;
import cn.yan.luowowo.service.UserInfoService;
import cn.yan.luowowo.util.AssertUtil;
import cn.yan.luowowo.util.Consts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Optional;
import java.util.UUID;

@Service
public class UserInfoServiceImpl implements UserInfoService{

    //注入UserInfoRepository
    @Autowired
    private UserInfoRepository userInfoRepository;

    //注入redis模板对象
    @Autowired
    private UserInfoRedisService userInfoRedisService;


    //保存用户方法
    @Override
    public void save(UserInfo user) {
        userInfoRepository.save(user);
    }

    //用户登录的方法
    @Override
    public UserInfo login(String phone, String password) {

        UserInfo user = userInfoRepository.findByPhoneAndPassword(phone,password);

        //判断用户是否存在
        if(user==null||!password.equals(user.getPassword())||!phone.equals(user.getPhone())){
            throw new LogicException("手机号或者密码错误！");
        }

        //将用户密码清空，防止密码暴露。
        user.setPassword(null);
        return user;
    }

    @Override
    public UserInfo get(String id) {
        Optional<UserInfo> op = userInfoRepository.findById(id);

        //如果op里面有值则返回该值，没有则返回null
        return op.orElse(null);
    }

    /*
    校验手机号码
     */
    @Override
    public boolean checkPhone(String phone) {

        UserInfo userInfo = userInfoRepository.findByPhone(phone);

        if(userInfo!=null){
            return true;
        }else {
            return false;
        }

    }

    @Override
    public void sendVerifyCode(String phone, String smsUrl, String smsSign, String smsAppkey) {

        //生成验证码
       String code = UUID.randomUUID().toString().replaceAll("-","").substring(0,4);

       //发送信息
        StringBuilder sb = new StringBuilder(100);
        sb.append("【一滩旅游网】,(登录验证码)").append(code).append("，请在")
                .append(Consts.VERIFY_CODE_VAI_TIME).append("分钟内使用");
        /*发送信息
         *sms.url=https://way.jd.com/chonry/smsnotice?sign={1}&mobile={2}&content={3}&appkey={4}
         * https://way.jd.com/chonry/smsnotice?sign=【创瑞云】&mobile=17755324095&content=您的本次的验证码是：0086。&appkey=5be97e29288f19a9bf59b21d61c5aa63
         */
        //java中发送http请求。RestTemplate
        RestTemplate restTemplate = new RestTemplate();
        //get的方式发起请求，参数一：路劲，参数2：返回值数据类型，
        String forObject = restTemplate.getForObject(smsUrl, String.class,smsSign,phone,sb.toString(),smsAppkey);
        System.out.println(forObject+code);

        //根据返回值判断是否发送成功
        if(!forObject.contains("SUCCESS")){
           throw new LogicException("短信发送失败");
        }

        //缓存信息到redis,有效时间为5分钟
        userInfoRedisService.sendVerifyCode(phone,code);
    }

    @Override
    public void regist (String phone, String nickname, String password, String rpassword, String verifyCode) {
        //判断参数是否一致
        //断言的方式。
        AssertUtil.hasLength(phone,"手机号码不能为空");
        AssertUtil.hasLength(nickname,"昵称不能为空");
        AssertUtil.hasLength(password,"密码不能为空");
        AssertUtil.hasLength(rpassword,"确认密码不能为空");
        AssertUtil.hasLength(verifyCode,"验证码不能为空");
       //判断密码是否与确认密码一致
        AssertUtil.isEquest(password,rpassword,"两次密码不一致");
        //判断手机号码
        if (this.checkPhone(phone)) {

            throw new LogicException("手机号码已被注册！");
        }
        //判断验证码
        //redis中的验证码
        String code = userInfoRedisService.getVerifyCode(phone);

        if(code == null || !verifyCode.equalsIgnoreCase(code)){
            throw new LogicException("验证码失效或者错误！");

        }
        //注册
        UserInfo user = new UserInfo();
        user.setPhone(phone);
        user.setNickname(nickname);
        user.setPassword(password);
        user.setEmail("");
        user.setCity("");
        user.setHeadImgUrl("/images/touxiang.jpg");
        user.setInfo("");
        user.setLevel(1);
        user.setState(UserInfo.STATE_NORMAL);
        this.save(user);

    }



}
